import notification from "@/services/notification";
import { observable, action,makeObservable } from 'mobx';
import Contracts from "@/services/contracts";
import ContractModel from "@/store/models/ContractModel";
import GlobalFunctions from '@/store/globalFunctions';
import Workflow from "@/services/workflow";
import CheckDialog from "@/components/workflow/CheckDialog";
import { currentUser } from "@/services/auth";
import ContractApply from "@/services/contractapply";
import moment from "moment";

class ContractStore {
  @observable contractModel = new ContractModel(0,0);
  constructor() {
    makeObservable(this)
  }
  @action initStore(id,isbulu) {
    this.init(id,isbulu);
  }

  init(id,isbulu) {
    if (id !== "0" && id !== 0) {
      Contracts.get({ id: id }).then(data => {
        this.contractModel = ContractModel.fromJS(data);
        Workflow.edit({ bill: "contracts", billtype: 0, billid: id, userid: currentUser.id }).then(data1 => {
          if (data1.length > 0) {
            this.contractModel.setBilledit(data1[0]);
          }
        }).catch(error => {
        });
        
      }).catch(error => {
        this.contractModel = new ContractModel(id,isbulu);
        if(isbulu ===0 || isbulu ==="0" ||isbulu ===1 || isbulu ==="1"){
          this.getcode("contracts",moment(),0,"code");
        }

      });
    } else {
      Contracts.getid({ id: 0 }).then(data => {
        this.contractModel = new ContractModel(data[0].id,isbulu);
        if(isbulu ===0 || isbulu ==="0" ||isbulu ===1 || isbulu ==="1"){
          this.getcode("contracts",moment(),0,"code");
        }
      });
    }
  }
  getcode(tblname,bill_date,type,tblfield) {
    ContractApply.getcode( {tblname: tblname,bill_date: bill_date,type: type,tblfield: tblfield,}).then(data => {
      this.contractModel.setCode(data[0].code);
    }).catch(error => {
      notification.error(error.message, error.detailedMessage);
    });
  };

  dataSave() {
    if(!currentUser.isDefault){
      notification.error("没有权限.");
      return false;
    }
 
    if(this.contractModel.xiuzhengupload){
      notification.error("修正格式上传，已自动保存！");
      return false;
    }
    // if (this.child.state.departmentid !==this.state.departmentid && templateid>1){
    //   notification.error("修改经办部门后，同时要修改对应合同模板，不能保存！");
    //   return false;
    // }
    if(this.contractModel.templatecontent.length<10){
      notification.error("请先提交合同正文！");
      return false;
    }
    if(this.contractModel.status ===0 && currentUser.id !==this.contractModel.userid){
      notification.error("草稿状态，不是制单人，不能保存！");
      return false;
    }
    if(this.contractModel.status ===2){
      if(this.contractModel.recordcodeold ===this.contractModel.recordcode && this.contractModel.officialcode === this.contractModel.officialcode &&
        this.contractModel.sign_dateold ===this.contractModel.sign_date && this.contractModel.start_date === this.contractModel.start_dateold &&
        this.contractModel.end_dateold === this.contractModel.end_date ){
        notification.error("已审批，不能保存！");
        return false;
      }
      if(!GlobalFunctions.isEmptyobj(this.contractModel.recordcodeold) && !currentUser.isAdmin){
        notification.error("备案号已存在，只有系统管理员可以修改，不能保存！");
        return false;
      }
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.contracttype)){
      notification.error("合同类别不能为空");
      return false;
    }else{
      if(this.contractModel.contracttype.length<1){
        notification.error("合同类别不能为空");
        return false;
      }
    }
    if(this.contractModel.contracttype.indexOf("框架协议") >=0){
      this.contractModel.budgetcode ="";
      this.contractModel.pay_direction=10;
      this.contractModel.zhengcai=0;
      this.contractModel.puremployeeid=0;
      this.contractModel.pricetype=10;
      this.contractModel.amount=0;
      this.contractModel.amount_words="";
      this.contractModel.amounttype =[];
    }else{
      if(GlobalFunctions.isEmptyobj(this.contractModel.pay_direction)){
        notification.error("收付方向不能为空");
        return false;
      }
      if(GlobalFunctions.isEmptyobj(this.contractModel.pricetype)){
        notification.error("合同类型不能为空");
        return false;
      }
      if(this.contractModel.amounttype.length===0){
        notification.error("资金类别不能为空！");
        return false;
      }
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.employeeid)){
      notification.error("经办人不能为空！");
      return false;
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.departmentid)){
      notification.error("经办部门不能为空");
      return false;
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.code)){
      notification.error("合同编号不能为空");
      return false;
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.name)){
      notification.error("合同名称不能为空");
      return false;
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.type)){
      this.contractModel.type=[]
      //notification.error("合同分类不能为空");
      //return;
    }
    if(this.contractModel.empowersex==="是"){
      if(GlobalFunctions.isEmptyobj(this.contractModel.empowerperson)){
        notification.error("授权代理人不能为空");
        return false;
      }
      if(GlobalFunctions.isEmptyobj(this.contractModel.empowerduties)){
        notification.error("代理人职务不能为空");
        return false;
      }
    }
    if(!GlobalFunctions.isEmptyobj(this.contractModel.message)){
      if(this.contractModel.message.length>1050){
        notification.error("重要条款不能超过1000字,现在有"+this.contractModel.message.length+"字");
        return false;
      }
    }
    if(this.contractModel.pricetype===0){
      if(this.contractModel.amount<1){
        notification.error("总价合同金额不能为空");
        return false;
      }
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.party_aid)){
      notification.error("甲方不能为空");
      return false;
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.message)){
      notification.error("重要条款不能为空");
      return false;
    }
    if(this.contractModel.isbulu<2){
      if(GlobalFunctions.isEmptyobj(this.contractModel.warn_date)){
        notification.error("提醒日期不能为空");
        return false;
      }
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.party_bid) || this.contractModel.party_bid==0){
      this.contractModel.party_bid=0;
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.party_cid)){
      this.contractModel.party_cid=0;
    }
    if(GlobalFunctions.isEmptyobj(this.contractModel.puremployeeid)){
      this.contractModel.puremployeeid=0;
    }


    let data={id: this.contractModel.id,//
            userid: this.contractModel.userid,//--操作员ID
            bill_date: this.contractModel.bill_date,//--日期
            employeeid: this.contractModel.employeeid,//--经办人
            departmentid: this.contractModel.departmentid,//--经办部门
            code: this.contractModel.code,//----合同编号
            name: this.contractModel.name,//--合同名称
            officialcode: this.contractModel.officialcode,
            budgetcode: this.contractModel.budgetcode,
            recordcode: this.contractModel.recordcode,
            puremployeeid:this.contractModel.puremployeeid,
            templateid: this.contractModel.templateid,
            templatecontent: this.contractModel.templatecontent,
            type: this.contractModel.type,//--合同类别
            party_aid: this.contractModel.party_aid,//--甲方ID
            party_bid: this.contractModel.party_bid ,//--乙方
            party_cid: this.contractModel.party_cid ,//--其它关联方
            pay_direction: this.contractModel.pay_direction ,//,--收付方向0-fukuan,1-shoukuan
            infrastructure: this.contractModel.infrastructure,
            zhengcai:this.contractModel.zhengcai,
            iskeyan:this.contractModel.iskeyan,
            iszhaobiao:this.contractModel.iszhaobiao,
            warnsealuser:this.contractModel.warnsealuser,
            isbulu:this.contractModel.isbulu,
            pricetype: this.contractModel.pricetype,
           sign_date: this.contractModel.sign_date,//--合同签订日期
           start_date: this.contractModel.start_date,//--合同开始日期
           end_date: this.contractModel.end_date,//--合同终止日期
           warn_date: this.contractModel.warn_date,
           warn_checkdate:this.contractModel.warn_checkdate,
           warn_message:this.contractModel.warn_message,//提醒内容
           warn_check:this.contractModel.warn_check,//审核提醒
           volumepurchase:this.contractModel.volumepurchase,
            amount: this.contractModel.amount,//--金额
            amount_words:this.contractModel.amount_words,//----合同金额(大写)
            amounttype: this.contractModel.amounttype,
            contracttype: this.contractModel.contracttype,
            status: this.contractModel.status,//--状态
            sourcetype: this.contractModel.sourcetype,
            sourceid: this.contractModel.sourceid,
            empowerperson: this.contractModel.empowerperson,//授权人
            empowersex: this.contractModel.empowersex,//性别
            empowerduties: this.contractModel.empowerduties,//职务
            agreementcount: this.contractModel.agreementcount,//协议份数
            message: this.contractModel.message}
    if(this.contractModel.isnew) {
      Contracts.create(data)
        .then(() => {
          this.init(this.contractModel.id,this.contractModel.isbulu);
          notification.success("合同新增成功.");
          return true;
        })
        .catch(error => {
          notification.error(error.message, error.response.data.message);
          return false;
        });
    }else{
      Contracts.save(data)
        .then(() => {
          notification.success("合同修改成功.");
          return true;
        })
        .catch(error => {
          notification.error(error.message, error.response.data.message);
          return false;
        });
    }
  };
  dataDelete() {
    Contracts.delete({ id: this.contractModel.id }).then(() => {
      notification.success("删除成功.");
      this.init(0,this.contractModel.isbulu);
    }).catch(error => {
      notification.error("删除失败", error.response.data.message);
    });

  };
  billCheck(userid) {
    if(!currentUser.isAudit){
      if (this.contractModel.status===0 || (this.contractModel.status === 1 && this.contractModel.userid === currentUser.id)){

      }else{
        notification.error("没有权限.");
        return;
      }
    }
    if(this.contractModel.isnew){
      this.dataSave();
      return ;
    }
    let item = {
      bill: "contracts",
      billtype: 0,
      billid: this.contractModel.id,
      next_type: 1,
      message:  "<div>同意</div>",
      userid: userid,
      billdate: this.contractModel.bill_date.format('YYYY-MM-DD'),
      orgunitid: this.contractModel.departmentid,
      status: this.contractModel.status,
      warnsealuser: this.contractModel.warnsealuser,
      billuserid: this.contractModel.userid,
    }
    // if (this.contractModel.status === 0) {
    //   Workflow.check(item).then(data => {
    //     if (data[0].flag === 0) {
    //       this.init(this.contractModel.id,this.contractModel.isbulu);
    //       notification.success(data[0].message);
    //     } else {
    //       notification.error(data[0].message);
    //     }
    //   })
    //     .catch(error => {
    //       notification.error(error.message, error.detailedMessage);
    //     });
    // } else {
      CheckDialog.showModal({ bill_check: item })
        .onClose((result = {}) => {
          if (result.success) {
            this.init(this.contractModel.id,this.contractModel.isbulu);
          }
        }).onDismiss(() => {
        });
    // }
  };
}

export default ContractStore;